package com.linghu.qqservice.service;

import com.linghu.qqcommon.Message;
import com.linghu.qqcommon.MessageType;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author 令狐荣豪
 * @version 1.0
 */
public class SendNewsToAllService implements Runnable{
    private Scanner scanner=new Scanner(System.in);

    @Override
    public void run() {
        while (true) {//为了可以多次推送新闻，加入while循环
            System.out.println("请输入服务器要推送的新闻(输入exit表示退出推送新闻服务)：");
            String news = scanner.next();
            if ("exit".equals(news)){
                break;
            }
            //构建一个消息，群发消息
            Message message = new Message();
            message.setSender("服务器");
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
            message.setContent(news);
            message.setSendtime(new Date().toString());
            System.out.println("服务器推送消息给所有人：" + news);

            //遍历当前所有通讯线程，得到socket，并发送messa对象
            HashMap<String, ServerConnectClientThread> hm = ManagerClientThreads.getHm();
            Iterator<String> iterator = hm.keySet().iterator();
            while (iterator.hasNext()) {
                String onLineUserId = iterator.next().toString();
                ServerConnectClientThread serverConnectClientThread = hm.get(onLineUserId);
                try {
                    ObjectOutputStream oos = new
                            ObjectOutputStream(serverConnectClientThread.getSocket().getOutputStream());
                    oos.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
